The array length in Java is the number of elements that an array can hold. It is a final variable that is part of the array object. The array length is set when the array is created and cannot be changed.
To get the length of an array, you can use the length property. The following syntax shows how to get the length of an array:
Java array lengtharray_name.length
For example, the following code shows how to get the length of an array of integers:
Array.length example
public class Main{
public static void main(String[] args){
int[] myArray = {1, 2, 3, 4, 5};
int arrayLength = myArray.length;
System.out.println("The array length is: " + arrayLength);
}
}
Output
The array length is: 5
The array length is useful for iterating over the elements of an array. For example, the following code shows how to use a for loop to iterate over the elements of an array and print them to the console:
Java array iteration using length
public class Main{
public static void main(String[] args){
int[] myArray = {1, 2, 3, 4, 5};
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
}
}
Output
1
2
3
4
5
The array length is also useful for checking the bounds of an array. For example, the following code shows how to check if an index is within the bounds of an array:
Java
int[] myArray = {1, 2, 3, 4, 5};
if (index >= 0 && index < myArray.length) {
// The index is within the bounds of the array
} else {
// The index is outside of the bounds of the array
}
It is important to check the bounds of an array before accessing an element in the array. If you try to access an element that is outside of the bounds of the array, you will get an ArrayIndexOutOfBoundsException.